<?php
namespace app\index\controller;
use app\common\controller\IndexBase;
use app\common\extend\alipay\Alipay;
use app\common\extend\wechat\WechatPay;
use app\common\extend\wechat\WechatJsapi;
class Course extends IndexBase
{
    /**
     * 课程搜索
     */
    public function search()
    {
        $param = $this->request->param();
        $key='%'.$param['keywords'].'%';
        $videoCourse=model('videoCourse')->field(['id','title','price','picture','type','teacher_id'])->where('title','like',$key)->where(['status'=>1])->select();
        foreach ($videoCourse as $k=> $value) {
            $videoCourse[$k]['stuNum']=getUserNum($videoCourse[$k]['id'],1);
            $videoCourse[$k]['teacher'] =getTeacherName($videoCourse[$k]['teacher_id']);
        }
        $liveCourse=model('liveCourse')->field(['id','title','price','picture','type','teacher_id'])->where('title','like',$key)->where(['status'=>1])->select();
        foreach ($liveCourse as $k=> $value) {
            $liveCourse[$k]['stuNum']=getUserNum($liveCourse[$k]['id'],2);
            $liveCourse[$k]['teacher'] =getTeacherName($liveCourse[$k]['teacher_id']);
        }
        $allCourse=array_merge($videoCourse,$liveCourse);
        return $this->fetch('search',['allCourse'=>$allCourse]);
    }
    /**
     * 课程详情信息
     */
    public function info()
    {
        session('returnUrl',$this->request->url());
        $param = $this->request->param();
        if(empty(hashids_decode(input('type'))) || empty(hashids_decode(input('id')))){
            throw new \think\exception\HttpException(404, '异常消息', null);
        }
        $param['id']=hashids_decode($param['id']);
        $param['type']=hashids_decode($param['type']);
        $videotuijian=model('videoCourse')->orderRaw('rand()')->where(['is_hot'=>1,'status'=>1])->limit(2)->select();
        $livetuijian=model('liveCourse')->orderRaw('rand()')->where(['is_hot'=>1,'status'=>1])->limit(2)->select();
        $tuijian=array_merge($videotuijian,$livetuijian);
        if(db('favourite')->where(['uid'=>is_user_login(),'cid'=>$param['id'],'type'=>$param['type']])->find()){
            $isfavourite='layui-hide';
            $nofavourite='';
        }else{
            $nofavourite='layui-hide';
            $isfavourite='';
        }
        switch ($param['type'])
        {
            case 1:
                model('videoCourse')->where(['id'=>$param['id']])->setInc('views');
                $courseinfo = model('videoCourse')->where(['id'=>$param['id']])->find();
                $section=model('videoCourse')->getSection($param['id']);
                $comment=model('comment')->where(['cid'=>$courseinfo['id'],'cstype'=>1])->limit(10)->order('addtime desc')->paginate(10);
                $material=model('material')->where('id', 'in', json_to_array($courseinfo['material_id']))->order('addtime desc')->select();
                $teacherInfo=model('cooperate')->where('id',$courseinfo['teacher_id'])->find();
                $isBuy=$this->isBuy(is_user_login(),$courseinfo['id'],$param['type']);
                $lastStudy=getLastStudy($param['id'],$param['type']);
                if($isBuy){
                    $this->redirect(url('index/user/mylearn', ['id'=>hashids_encode($courseinfo['id']),'type'=>hashids_encode($courseinfo['type'])]));
                }else{
                    return $this->fetch('info',['title'=>$courseinfo['title'],'lastStudy'=>$lastStudy,'info'=>$courseinfo,'secList'=>$section,'comment'=>$comment,'material'=>$material,'teacherInfo'=>$teacherInfo,'tuijian'=>$tuijian,'isBuy'=>$isBuy,'isfavourite'=>$isfavourite,'nofavourite'=>$nofavourite]);
                }
                break;
            case 2:
                model('liveCourse')->where(['id'=>$param['id']])->setInc('views');
                $courseinfo = model('liveCourse')->where(['id'=>$param['id']])->find();
                $section=model('liveCourse')->getSection($param['id']);
                $comment=model('comment')->where(['cid'=>$courseinfo['id'],'cstype'=>2])->limit(10)->order('addtime desc')->paginate(10);
                $material=model('material')->where('id', 'in', json_to_array($courseinfo['material_id']))->order('addtime desc')->select();
                $teacherInfo=model('cooperate')->where('id',$courseinfo['teacher_id'])->find();
                $isBuy=$this->isBuy(is_user_login(),$courseinfo['id'],$param['type']);
                $lastStudy=getLastStudy($param['id'],$param['type']);
                $surplus=$courseinfo['limit']-getUserNum($courseinfo['id'],2);
                if($isBuy){
                    $this->redirect(url('index/user/mylearn', ['id'=>hashids_encode($courseinfo['id']),'type'=>hashids_encode($courseinfo['type'])]));
                }else{
                    return $this->fetch('live',['title'=>$courseinfo['title'],'lastStudy'=>$lastStudy,'info'=>$courseinfo,'surplus'=>$surplus,'secList'=>$section,'comment'=>$comment,'material'=>$material,'teacherInfo'=>$teacherInfo,'tuijian'=>$tuijian,'isBuy'=>$isBuy,'isfavourite'=>$isfavourite,'nofavourite'=>$nofavourite]);
                }
                break;
        }
    }
    /**
     * 点播课程首页
     */
    public function videoindex()
    {
        $mobileCate=model('courseCategory')->where(['pid'=>0])->order('sort_order asc')->select();
        foreach ($mobileCate as $k=> $value) {
            $mobileCate[$k]['secondclass']=model('courseCategory')->where(['pid'=>$mobileCate[$k]['id']])->order('sort_order asc')->select();
        }
        $parent=model('courseCategory')->where(['pid'=>0])->order('sort_order asc')->select();
        $category=model('courseCategory')->order('sort_order asc')->select();
        $param = $this->request->param();
        $where=$this->getCateId($category,$param);
        if(!empty($param['parent'])){
            $secondclass=model('courseCategory')->where(['pid'=>$param['parent']])->order('sort_order asc')->select();
        }
        if(!empty($param['second'])){
            $thirdclass=model('courseCategory')->where(['pid'=>$param['second']])->order('sort_order asc')->select();
        }
        if(request()->isMobile()){
            $videoCourse=model('videoCourse')->order('sort_order asc,addtime desc')->where('is_top',1)->where('cid','in',$where)->select();
        }else{
            $videoCourse=model('videoCourse')->order('sort_order asc,addtime desc')->where('is_top',1)->where('cid','in',$where)->paginate(config('page_number'),false,[ 'query' => request()->param()]);
        }
        return $this->fetch('index',['mobileCate'=>$mobileCate,'type'=>'video','parent'=>$parent,'second'=>$secondclass,'third'=>$thirdclass,'list'=>$videoCourse,'title'=>'录播课程']);
    }
    /**
     * 直播课程首页
     */
    public function liveindex()
    {
        $mobileCate=model('courseCategory')->where(['pid'=>0])->order('sort_order asc')->select();
        foreach ($mobileCate as $k=> $value) {
            $mobileCate[$k]['secondclass']=model('courseCategory')->where(['pid'=>$mobileCate[$k]['id']])->order('sort_order asc')->select();
        }
        $parent=model('courseCategory')->where(['pid'=>0])->order('sort_order asc')->select();
        $category=model('courseCategory')->order('sort_order asc')->select();
        $param = $this->request->param();
        $where=$this->getCateId($category,$param);
        if(!empty($param['parent'])){
            $secondclass=model('courseCategory')->where(['pid'=>$param['parent']])->order('sort_order asc')->select();
        }
        if(!empty($param['second'])){
            $thirdclass=model('courseCategory')->where(['pid'=>$param['second']])->order('sort_order asc')->select();
        }
        if(request()->isMobile()){
            $liveCourse=model('liveCourse')->order('sort_order asc,addtime desc')->where('is_top',1)->where('cid','in',$where)->select();
        }else{
            $liveCourse=model('liveCourse')->order('sort_order asc,addtime desc')->where('is_top',1)->where('cid','in',$where)->paginate(config('page_number'),false,[ 'query' => request()->param()]);
        }
        return $this->fetch('index',['mobileCate'=>$mobileCate,'type'=>'live','parent'=>$parent,'second'=>$secondclass,'third'=>$thirdclass,'list'=>$liveCourse,'title'=>'直播课程']);
    }
    /**
     * 获取课程分类ID,用于筛选课程
     */
    public function getCateId($category,$param){
        if(!empty($param['third'])){
            $childId[]=$param['third'];
        }elseif(!empty($param['second'])){
            $childId=getMenuTree($category,$param['second']);
            $childId[]=(int)$param['second'];
        }elseif(!empty($param['parent'])){
            $childId=getMenuTree($category,$param['parent']);
            $childId[]=(int)$param['parent'];
        }
        if(empty($childId)){
            $childId=$childId=getMenuTree($category,0);
        }
        return $childId;
    }
    /**
     * 创建订单
     */
    public function creatorder(){
        !$this->checkLogin() && $this->redirect(url('index/user/login'));
        $param = $this->request->param();
        $param['id']=hashids_decode($param['id']);
        $param['type']=hashids_decode($param['type']);
        $mycoupon=model('coupon')->order('id desc')->where(['userId'=>is_user_login(),'status'=>0,'usestatus'=>0])->select();
        $courseinfo=$this->getCouseInfo($param['id'],$param['type']);
        if($courseinfo['type']==3){
            foreach($courseinfo['cids'] as $k=>$v) {
                $ids=explode('-',$courseinfo['cids'][$k],2);
                if($ids[0]==1){
                    $teacherId[$ids[1]]=model('videoCourse')->where(['id'=>$ids[1]])->field('teacher_id')->value('teacher_id');
                }else{
                    $teacherId[$ids[1]]=model('liveCourse')->where(['id'=>$ids[1]])->field('teacher_id')->value('teacher_id');
                }
            }
        }
        if($cuxiaoPrice=flashsale($param['id'],$courseinfo['type'], $courseinfo['price'],3)){
            $order['total']=$cuxiaoPrice;
            $courseinfo['price']=$cuxiaoPrice;
        }else{
            $order['total']= $courseinfo['price'];
        }
        if ($this->request->isPost()){
            if(($coupon=model('coupon')->where(['code'=>$param['usedCoupon']])->find()) && !empty($param['usedCoupon'])){
                $order['total']= round($courseinfo['price']*$coupon['rate']/10,1);
            }else{
                $order['total']= $courseinfo['price'];
            }
            $order['title']=$courseinfo['title'];
            $order['ctype']=$courseinfo['type'];
            $order['state']=0;
            $order['addtime']=date('Y-m-d h:i:s', time());
            $order['uid']=is_user_login();
            if($courseinfo['type']==3){
                $order['tid']=$courseinfo['headteacher'];
            }else{
                $order['tid']=$courseinfo['teacher_id'];
            }
            $order['paytype']=$param['payment'];
            $order['cid']=$param['id'];
            $order['orderid']= date('Ymdhms');
            $this->checkBuied($order['uid'],$order['cid'],$order['ctype']);
            if($info=model('order')->where(['ctype'=>$courseinfo['type'],'cid'=>$param['id'],'uid'=>is_user_login()])->find()){
                $order['id']=$info['id'];
                $res=$this->update('order',$order);
            }else{
                $res=$this->insert('order',$order);
            }
            if ($res === true) {
                db('coupon')->where(['code'=>$param['usedCoupon']])->update(['usestatus'=>1]);
                if($order['total']==0){
                    $this->update('order', ['paytype'=>'free','state'=>1,'orderid'=>$order['orderid']], $rule = true, $field = true, $key = 'orderid');
                    if($info=model('userCourse')->where(['uid'=>$order['uid'],'cid'=>$order['cid'],'type'=>$order['ctype']])->find()){
                        model('userCourse')->where('id',$info['id'])->setField('addtime', date('Y-m-d h:i:s', time()));
                    }else{
                        $this->insert('userCourse',['uid'=>$order['uid'],'cid'=>$order['cid'],'type'=>$order['ctype'],'state'=>1,'addtime'=>date('Y-m-d h:i:s', time())]);
                    }
                    $this->success('添加成功',url('index/course/payResult',['orderid'=>$order['orderid']]));
                }else{
                    return $this->payment($order);
                }
            } else {
                $this->error($this->errorMsg);
            }
        }else{
            if($courseinfo['price']==0){
                return $this->fetch('freeorder',['courseInfo'=>$courseinfo]);
            }else{
                return $this->fetch('creatorder',['teacherIds'=>$teacherId,'courseInfo'=>$courseinfo,'mycoupon'=>$mycoupon]);
            }
        }
    }
    /**
     * 获取班级课程id
     */
    function getClassroomCourseIds($classroomId){
        $courseinfo = model('classroom')->where(['id'=>$classroomId])->find();
        $cids=json_to_array($courseinfo['cids']);
        foreach( $cids as $k=>$v) {
            $ids=explode('-',$cids[$k],2);
            $ids[0]==1?$videoIds[]=$ids[1]:$liveIds[]=$ids[1];
        }
        $data=['videoIds'=>$videoIds,'liveIds'=>$liveIds];
        return $data;
    }
    /**
     * 使用优惠券操作
     */
    function couponUsed(){
        $param = $this->request->param();
        if(flashsale($param['cid'],$param['type'],$param['price'],$param['usetype'])){
            $res=['code'=>1,'msg'=>'促销课程，不支持使用优惠券'];
        }else{
            if($data=model('coupon')->where(['code'=>$param['coupon']])->find()){
                if ($data['usestatus']==1) {
                    $res=['code'=>1,'msg'=>'该优惠券已被使用'];
                } elseif ($data['status']==1) {
                    $res=['code'=>1,'msg'=>'该优惠券已被禁用'];
                } else {
                    $res=['code'=>0,'rate'=>$data['rate']];
                }
            }else{
                $res=['code'=>1,'msg'=>'输入的优惠券无效'];
            }
        }
        echo json_encode($res);
    }
    /**
     * 未支付订单重新支付
     */
    function  repay(){
        $order=model('order')->where('id',input('id'))->find();
        $courseinfo=$this->getCouseInfo($order['cid'],$order['ctype']);
        $order['title']=$courseinfo['title'];
        if($order['total']==0){
            $this->update('order', ['state'=>1,'orderid'=>$order['orderid']], $rule = true, $field = true, $key = 'orderid');
            if($info=model('userCourse')->where(['uid'=>$order['uid'],'cid'=>$order['cid'],'type'=>$order['ctype']])->find()){
                model('userCourse')->where('id',$info['id'])->setField('addtime', date('Y-m-d h:i:s', time()));
            }else{
                $this->insert('userCourse',['uid'=>$order['uid'],'cid'=>$order['cid'],'type'=>$order['ctype'],'state'=>1,'addtime'=>date('Y-m-d h:i:s', time())]);
            }
            if($order['ctype']==3){
                $getIds=$this->getClassroomCourseIds($order['cid']);
                $videoIds=$getIds['videoIds'];
                $liveIds=$getIds['liveIds'];
                $this->batchAddCourse($order['uid'],$videoIds,$liveIds,$order['cid']);
            }
            $this->success('添加成功',url('index/course/payResult',['orderid'=>$order['orderid']]));
        }else{
            return $this->payment($order);
        }
    }
    /**
     * 订单支付
     */
    function payment($order){
        !$this->checkLogin() && $this->redirect(url('index/user/login'));
        if($order['paytype']=='alipay'){
            return  $this->alipay($order);
        }
        if($order['paytype']=='wxpay'){
            return  $this->wxpay($order);
        }
        if($order['paytype']=='yuepay'){
            return  $this->yuepay($order);
        }
    }
    /**
     * 支付宝支付
     */
    function alipay($order){
        if(request()->isMobile()){
            $payData = [
                'order_no' =>$order['orderid'],
                'order_price' => $order['total'],
                'subject' => $order['title'],
                'notify_url' =>is_https().get_domain(). '/index/course/notifyalipay/',
                'return_url'=>is_https().get_domain(). '/index/course/return_url/',
            ];
            $alipay = new Alipay($this->alipayH5Config());
            $info = $alipay->placeWap($payData);
            return $this->fetch('aliPay',['info'=>$info['html_form'],]);
        }else{
            $payData = [
                'order_no' =>$order['orderid'],
                'order_price' => $order['total'],
                'subject' => $order['title'],
                'notify_url' =>is_https().get_domain(). '/index/course/notifyalipay/',
                'return_url'=>is_https().get_domain(). '/index/course/return_url/',
            ];
            $alipay = new Alipay($this->alipayConfig());
            $info = $alipay->placePage($payData);
            return $this->fetch('aliPay',['info'=>$info['html_form'],]);
        }
    }
    /**
     * 微信支付
     */
    function wxpay($order){
        if(request()->isMobile()){
            if(in_wechat()){
                $data=$this->wechatJsApiConfig();
                session('orderId',$order['orderid']);
                $WechatJsapi=new WechatJsapi($data);
                $WechatJsapi->getCode(is_https().get_domain().'/index/course/getcode/');
            }else{
                $redirect_url=is_https().get_domain().'/ordersettle/'.$order['orderid'];
                $data=$this->wechatH5Config();
                $name="微信支付";
                $payData = [
                    'body'=>$order['title'],
                    'out_trade_no'=>$order['orderid'],
                    'total_fee'=> $order['total']*100,
                    'trade_type'=> 'MWEB',
                    'wap_url'=>is_https().get_domain(),
                    'wap_name'=>$name,
                    'notify_url'=>get_domain(). '/index/course/notifywechat/',
                    'scene_info'=>'{"h5_info": {"type":"Wap","wap_url": "'.is_https().get_domain().'","wap_name": "'.$name.'"}}'
                ];
                $wechatPay = new WechatPay($data);
                $info = $wechatPay->unifiedOrder($payData);
                $url_encode_redirect=urlencode($redirect_url);
                $url = $info['mweb_url'].'&redirect_url='.$url_encode_redirect;
                echo "<script>window.location.href='".$url."';</script>";
            }
        }else{
            $payData = [
                'body' => $order['title'],
                'out_trade_no' =>$order['orderid'],
                'total_fee' => $order['total']*100,
                'trade_type' => 'NATIVE',
                'notify_url' =>get_domain(). '/index/course/notifywechat/',
                'expire'=>'600'
            ];
            $wechatPay = new WechatPay($this->wechatJsApiConfig());
            $info = $wechatPay->unifiedOrder($payData);
            $url=str_replace("/","*",$info['code_url']);
            $url=str_replace("?","$",$url);
            $info['code_url']=urlencode($url);
            $info['return_code'] == 'FAIL';
            $info['result_code'] == 'FAIL';
            return $this->fetch('wechatPay',['info'=>$info,'order'=>$order]);
        }
    }
    function getcode(){
        $param = $this->request->param();
        if($param['type']=='login'){
            $this->redirect('api/author/appcallbac', ['code' => $param['code']]);
        }else{
            $data=$this->wechatAPPConfig();
            $WechatJsapi=new WechatJsapi($data);
            $AccessToken=$WechatJsapi->getAccessToken($param['code']);
            $order=model('order')->where('orderid',session('orderId'))->find();
            $courseinfo=$this->getCouseInfo($order['cid'],$order['ctype']);
            $order['title']=$courseinfo['title'];
            $payData = [
                'body'=>$order['title'],
                'out_trade_no'=>$order['orderid'],
                'total_fee'=> $order['total']*100,
                'trade_type'=> 'JSAPI',
                'notify_url'=>get_domain(). '/index/course/notifywechat/',
                'openid'=>$AccessToken['openid']
            ];
            $wechatPay = new WechatPay($data);
            $info = $wechatPay->unifiedOrder($payData);
            $jsApiParameters= $wechatPay->getJsapiParam($info['prepay_id']);
            return $this->fetch('wechatJsPay',['jsApiParameters'=>$jsApiParameters,'order'=>$order]);
        }

    }
    /**
     * 余额支付
     */
    function yuepay($orderInfo){
        $userInfo=model('user')->where(['id'=>is_user_login()])->find();
        $userInfo['yue']<$orderInfo['total'] && $this->error('余额不足，请先充值');
        $this->update('order', ['profit'=>$orderInfo['total']*config('bili'),'state'=>1,'payorder'=>'','orderid'=>$orderInfo['orderid']], $rule = true, $field = true, $key = 'orderid');
        //添加到我的课程中，3为教师，若存在则跟新时间
        if($info=model('userCourse')->where(['uid'=>$orderInfo['uid'],'cid'=>$orderInfo['cid'],'type'=>$orderInfo['ctype']])->find()){
            $res=model('userCourse')->where('id',$info['id'])->setField('addtime', date('Y-m-d h:i:s', time()));
        }else{
            $res=$this->insert('userCourse',['uid'=>$orderInfo['uid'],'cid'=>$orderInfo['cid'],'type'=>$orderInfo['ctype'],'state'=>1,'addtime'=>date('Y-m-d h:i:s', time())]);
        }
        //教师提成分配，3为班级的教师盈利分配
        if($orderInfo['ctype']==3){
            $this->batchAddProfit($orderInfo['cid'],$orderInfo['total']);
        }else{
            if($profit=db('profit')->where(['tid'=>$orderInfo['tid']])->find()){
                db('profit')->where(['tid'=>$orderInfo['tid']])->update(['profit'=>$orderInfo['total']*config('bili')+$profit['profit']]);
            }else{
                db('profit')->insert(['tid'=>$orderInfo['tid'],'profit'=>$orderInfo['total']*config('bili')]);
            }
        }
        if($res){
            db('user')->where(['id'=>is_user_login()])->update(['yue'=>$userInfo['yue']-$orderInfo['total']]);
            $this->coupon('buy',$orderInfo['uid']);
            return  $this->payResult($orderInfo);
        }
    }
    /**
     * 微信回调处理
     */
    function notifywechat()
    {
        $wechatPay = new WechatPay($this->wechatConfig());
        $verify = $wechatPay->getNotifyData();
        if ($verify['return_code'] == 'SUCCESS' && $verify['result_code'] == 'SUCCESS') {
            $orderInfo = model('order')->where(['orderid'=>$verify['out_trade_no']])->find();
            if ($orderInfo['total']*100 == $verify['total_fee']) {
                $wechatPay->closeOrder($verify['out_trade_no']);
                $this->update('order', ['profit'=>$orderInfo['total']*config('bili'),'state'=>1,'payorder'=>$verify['transaction_id'],'orderid'=>$verify['out_trade_no']], $rule = true, $field = true, $key = 'orderid');
                if($info=model('userCourse')->where(['uid'=>$orderInfo['uid'],'cid'=>$orderInfo['cid'],'type'=>$orderInfo['ctype']])->find()){
                    model('userCourse')->where('id',$info['id'])->setField('addtime', date('Y-m-d h:i:s', time()));
                }else{
                    $this->insert('userCourse',['uid'=>$orderInfo['uid'],'cid'=>$orderInfo['cid'],'type'=>$orderInfo['ctype'],'state'=>1,'addtime'=>date('Y-m-d h:i:s', time())]);
                }
                if($orderInfo['ctype']==3){
                    $this->batchAddProfit($orderInfo['cid'],$orderInfo['total']);
                }else{
                    if($profit=db('profit')->where(['tid'=>$orderInfo['tid']])->find()){
                        db('profit')->where(['tid'=>$orderInfo['tid']])->update(['profit'=>$orderInfo['total']*config('bili')+$profit['profit']]);
                    }else{
                        db('profit')->insert(['tid'=>$orderInfo['tid'],'profit'=>$orderInfo['total']*config('bili')]);
                    }
                }
                $this->coupon('buy',$orderInfo['uid']);
                $wechatPay->replyNotify();
            } else {
                $this->error('订单金额出现错误');
            }
        } else {
            $this->error($verify['err_code_des']);
        }
    }
    /**
     * 支付宝回调处理
     */
    function notifyalipay()
    {
        $alipay = new Alipay($this->alipayConfig());
        $check = $alipay->rsaCheck($verify = $_POST);
        if($check) {
            $orderInfo = model('order')->where(['orderid'=>$verify['out_trade_no']])->find();
            if ($this->checkOrder($verify['out_trade_no'])) {
                $this->update('order', ['profit'=>$orderInfo['total']*config('bili'),'state'=>1,'payorder'=>$verify['trade_no'],
                    'orderid'=>$verify['out_trade_no']], $rule = true, $field = true, $key = 'orderid');
                if($info=model('userCourse')->where(['uid'=>$orderInfo['uid'],'cid'=>$orderInfo['cid'],'type'=>$orderInfo['ctype']])->find()){
                    model('userCourse')->where('id',$info['id'])->setField('addtime', date('Y-m-d h:i:s', time()));
                }else{
                    $this->insert('userCourse',['uid'=>$orderInfo['uid'],'cid'=>$orderInfo['cid'],'type'=>$orderInfo['ctype'],'state'=>1, 'addtime'=>date('Y-m-d h:i:s', time())]);
                }
                if($orderInfo['ctype']==3){
                    $this->batchAddProfit($orderInfo['cid'],$orderInfo['total']);
                }else{
                    if($profit=db('profit')->where(['tid'=>$orderInfo['tid']])->find()){
                        db('profit')->where(['tid'=>$orderInfo['tid']])->update(['profit'=>$orderInfo['total']*config('bili')+$profit['profit']]);
                    }else{
                        db('profit')->insert(['tid'=>$orderInfo['tid'],'profit'=>$orderInfo['total']*config('bili')]);
                    }
                }
                $this->coupon('buy',$orderInfo['uid']);
            }
            echo "success";
        }else {
            echo "fail";
        }
    }
    function return_url(){
        $alipay = new Alipay($this->alipayConfig());
        $check = $alipay->rsaCheck($verify = $_GET);
        if($check) {
            $orderInfo = model('order')->where(['orderid'=>$verify['out_trade_no']])->find();
            if ($this->checkOrder($verify['out_trade_no'])) {
                $this->update('order', ['profit'=>$orderInfo['total']*config('bili'),'state'=>1,'payorder'=>$verify['trade_no'],
                    'orderid'=>$verify['out_trade_no']], $rule = true, $field = true, $key = 'orderid');
                if($info=model('userCourse')->where(['uid'=>$orderInfo['uid'],'cid'=>$orderInfo['cid'],'type'=>$orderInfo['ctype']])->find()){
                    model('userCourse')->where('id',$info['id'])->setField('addtime', date('Y-m-d h:i:s', time()));
                }else{
                    $this->insert('userCourse',['uid'=>$orderInfo['uid'],'cid'=>$orderInfo['cid'],'type'=>$orderInfo['ctype'],'state'=>1, 'addtime'=>date('Y-m-d h:i:s', time())]);
                }
                if($orderInfo['ctype']==3){
                    $this->batchAddProfit($orderInfo['cid'],$orderInfo['total']);
                }else{
                    if($profit=db('profit')->where(['tid'=>$orderInfo['tid']])->find()){
                        db('profit')->where(['tid'=>$orderInfo['tid']])->update(['profit'=>$orderInfo['total']*config('bili')+$profit['profit']]);
                    }else{
                        db('profit')->insert(['tid'=>$orderInfo['tid'],'profit'=>$orderInfo['total']*config('bili')]);
                    }
                }
                $this->coupon('buy',$orderInfo['uid']);
            }
            return $this->redirect(url('index/course/payResult',['orderid'=>$orderInfo['orderid']]));
        }else {
            echo "fail";
        }
    }

    function checkOrder($out_trade_no){
        if(model('order')->where(['orderid'=>$out_trade_no])->value('state')==1){
            return false;
        }else{
            return true;
        };
    }
    /**
     * 购买班级成功，批量添加班级内课程到用户中心
     */
    function batchAddCourse($uid,$videoIds,$liveIds,$classroomId){
        if(!empty($videoIds)){
            foreach ($videoIds as $k=> $value) {
                if(!$res=model('user_course')->where(['uid' => $uid, 'cid' => $videoIds[$k], 'type' => 1])->find()){
                    $data[]=['uid'=>$uid,'cid'=>$videoIds[$k],'type'=>1,'state'=>1,'isclassroom'=>$classroomId, 'addtime'=>date('Y-m-d h:i:s', time())];
                }else{
                    model('user_course')->where('id',$res['id'])->setField(['addtime'=>date('Y-m-d h:i:s', time())]);
                }
            }
        }
        if(!empty($liveIds)){
            foreach ($liveIds as $k=> $value) {
                if(!$res=model('user_course')->where(['uid' => $uid, 'cid' => $liveIds[$k], 'type' => 2])->find()){
                    $data[]=['uid'=>$uid,'cid'=>$liveIds[$k],'type'=>2,'state'=>1,'isclassroom'=>$classroomId, 'addtime'=>date('Y-m-d h:i:s', time())];
                }else{
                    model('user_course')->where('id',$res['id'])->setField(['addtime'=>date('Y-m-d h:i:s', time())]);
                }
            }
        }
        if(!empty($data)){
            model('userCourse')->insertAll($data);
        }
    }
    /**
     * 购买班级成功，批量给各科教师分配收入
     */
    function batchAddProfit($classroomId,$price){
        $getIds=$this->getClassroomCourseIds($classroomId);
        $videoIds=$getIds['videoIds'];
        $liveIds=$getIds['liveIds'];
        $videoSumPrice = round(model('videoCourse')->where('id','in',$videoIds)->sum('price'));
        $liveSumPrice =round(model('liveCourse')->where('id','in',$liveIds)->sum('price'));
        $tallPrice=round($videoSumPrice+$liveSumPrice);
        foreach ($videoIds as $k=> $value) {
            $videoCourseInfo=model('videoCourse')->where(['id'=>$value])->field('teacher_id,price')->find();
            if($profit=db('profit')->where(['tid'=>$videoCourseInfo['teacher_id']])->find()){
                db('profit')->where(['tid'=>$videoCourseInfo['teacher_id']])->update(['profit'=>round(($price*($videoCourseInfo['price']/$tallPrice))*config('bili'))+$profit['profit']]);
            }else{
                db('profit')->insert(['tid'=>$videoCourseInfo['teacher_id'],'profit'=>(round($price*($videoCourseInfo['price']/$tallPrice))*config('bili'))]);
            }
        }
        foreach ($liveIds as $k=> $value) {
            $liveCourseInfo=model('liveCourse')->where(['id'=>$value])->field('teacher_id,price')->find();
            if($profit=db('profit')->where(['tid'=>$liveCourseInfo['teacher_id']])->find()){
                db('profit')->where(['tid'=>$liveCourseInfo['teacher_id']])->update(['profit'=>round(($price*($liveCourseInfo['price']/$tallPrice))*config('bili'))+$profit['profit']]);
            }else{
                db('profit')->insert(['tid'=>$liveCourseInfo['teacher_id'],'profit'=>(round($price*($liveCourseInfo['price']/$tallPrice))*config('bili'))]);
            }
        }
    }
    /**
     * 生成二维码
     */
    public function qrcode(){
        vendor('phpqrcode.phpqrcode');
        $param = $this->request->param();
        $url=str_replace("*","/",urldecode($param['url']));
        $url=str_replace("$","?",$url);
        $level = 'Q';
        $size = 6;
        \QRcode::png($url, false, $level, $size);
    }
    /**
     * 检测支付结果
     */
    public function checkPay(){
        $param = $this->request->param();
        $param['orderid']=$param['orderid'];
        $orderInfo = model('order')->where(['orderid'=>$param['orderid']])->value('state');
        if($orderInfo==1){
            $result['states']=true;
        }else{
            $result['states']=false;
        }
        $json_string = json_encode($result);
        echo $json_string;
    }
    /**
     * 微信手机支付订单处理等待
     */
    function ordersettle(){
        $param = $this->request->param();
        return $this->fetch('ordersettle',['orderid'=>$param['orderid']]);
    }
    function appordersettle(){
        $orderid=session('orderId');
        session('orderId',null);
        return $this->fetch('ordersettle',['orderid'=>$orderid]);
    }
    /**
     * 支付结果回显
     */
    public function payResult($orderInfo=''){
        if(empty($orderInfo)){
            $param = $this->request->param();
            $orderInfo=model('order')->where(['orderid'=>$param['orderid']])->find();
        }else{
            $orderInfo=model('order')->where(['orderid'=>$orderInfo['orderid']])->find();
        }
        $courseinfo=$this->getCouseInfo($orderInfo['cid'],$orderInfo['ctype']);
        return $this->fetch('payResult',['courseinfo'=>$courseinfo,'orderInfo'=>$orderInfo]);
    }
    /**
     * ajax检查是否购买了课程  课时ID
     */
    public function checkBuy(){
        $param = $this->request->param();
        if($param['type']==1){
            $sessionInfo=model('videoSection')->where(['id'=>$param['sid']])->find();
            $tid = model('videoCourse')->where(['id'=>$sessionInfo['csid']])->value('teacher_id');
        }
        if($param['type']==2){
            $sessionInfo=model('liveSection')->where(['id'=>$param['sid']])->find();
            $tid = model('liveCourse')->where(['id'=>$sessionInfo['csid']])->value('teacher_id');
        }
        $state=model('userCourse')->where(['cid'=>$sessionInfo['csid'],'type'=>$param['type'],'uid'=>is_user_login()])->find();
        $href=url('index/Course/learn',['id'=>hashids_encode($param['sid']),'type'=>hashids_encode($param['type'])]);
        $isInClassroom=$this->isInClassroom($sessionInfo['csid'],$param['type']);
        if($isInClassroom || $sessionInfo['previewtimes']>0 || $state || ($sessionInfo['isfree']==1) || ($tid==getTeacherIdByUid(is_user_login())) || (getAdminAuthId(is_admin_login())==1)){
            echo (json_encode(['code'=>'1','href'=>$href]));
        }else{
            echo (json_encode(['code'=>'0','msg'=>'请先购买课程']));
        }
    }
    /**
     * 课程学习
     */
    public function learn()
    {
        if(empty(hashids_decode(input('type'))) || empty(hashids_decode(input('id')))){
            throw new \think\exception\HttpException(404, '异常消息', null);
        }
        !$this->checkLogin() && $this->redirect(url('index/user/login'));
        $this->checkBuyPhp(hashids_decode(input('type')),hashids_decode(input('id')));
        $this->checkValid(hashids_decode(input('type')),hashids_decode(input('id')));
        if(hashids_decode(input('type'))==1){
            $sectionInfo=model('videoSection')->where(['id'=>hashids_decode(input('id'))])->find();
            $section=model('videoCourse')->getSection($sectionInfo['csid']);
            $note=model('notes')->where(['uid'=>is_user_login(),'cid'=>$sectionInfo['csid'],'sid'=>$sectionInfo['id'],'cstype'=>1])->order('addtime desc')->select();
            $comment=model('comment')->where(['cid'=>$sectionInfo['csid'],'sid'=>$sectionInfo['id'],'cstype'=>1])->limit(10)->order('addtime desc')->select();
            if($sectionInfo['sectype']==1){
                $tid = model('videoCourse')->where(['id'=>$sectionInfo['csid']])->value('teacher_id');
                $learnInfo=db('learned')->where(['uid'=>is_user_login(),'sid'=>$sectionInfo['id'],'type'=>$sectionInfo['coursetype']])->find();
                if($userInfo=model('user')->where(['id'=>is_user_login()])->find()){
                    $BulletScreen=$userInfo['username'].' '.$userInfo['mobile'];
                }else{
                    $BulletScreen=config('website.site_name');
                }
                $relBuy=model('userCourse')->where(['cid'=>$sectionInfo['csid'],'type'=>1,'uid'=>is_user_login()])->find();
                if($relBuy || $sectionInfo['isfree']==1 || ($tid==getTeacherIdByUid(is_user_login())) || (getAdminAuthId(is_admin_login())==1)){$sectionInfo['previewtimes']=0;}
                return $this->fetch('learn',['learnInfo'=>$learnInfo,'title'=>$sectionInfo['title'],'BulletScreen'=>$BulletScreen,'info'=>$sectionInfo,'secList'=>$section,'note'=>$note,'comment'=>$comment]);
            }
            if($sectionInfo['sectype']==2){
                return $this->fetch('audio',['title'=>$sectionInfo['title'],'info'=>$sectionInfo,'secList'=>$section,'note'=>$note,'comment'=>$comment]);
            }
            if($sectionInfo['sectype']==3){
                model('userCourse')->where(['uid'=>is_user_login(),'cid'=>$sectionInfo['csid']])->update(['nowstudy'=>$sectionInfo['id']]);
                return $this->fetch('document',['title'=>$sectionInfo['title'],'info'=>$sectionInfo,'secList'=>$section,'note'=>$note,'comment'=>$comment]);
            }
            if($sectionInfo['sectype']==4){
                $exam=model('exams')->where('id',$sectionInfo['paperid'])->find();
                $exam['examsetting']=json_to_array($exam['examsetting']);
                $exam['examquestions']=json_to_array($exam['examquestions']);
                $subQuestions=[];
                foreach ($exam['examquestions'] as $k => $value) {
                    if(get_question_mark($k)=='TiMao'){
                        foreach ($exam['examquestions'][$k] as $i => $value) {
                            $subQuestions[$value]=$this->getSubQuestions($value);
                        }
                    }
                }
                $exam['subQuestions']=$subQuestions;
                $myexam=model('myexam')->where(['uid'=>is_user_login(),'cid'=>$sectionInfo['csid'],'eid'=>$sectionInfo['paperid']])->find();
                $myexam['myanswer']=json_to_array($myexam['myanswer']);
                $myexam['myscore']=json_to_array($myexam['myscore']);
                $myexam['myresult']=json_to_array($myexam['myresult']);
                if($exam['examsetting']['examtype']==1 || $myexam['ispost']==1){
                    return $this->fetch('exam',['useType'=>4,'title'=>$sectionInfo['title'],'exam'=>$exam,'myexam'=>$myexam,'info'=>$sectionInfo,'secList'=>$section,'note'=>$note,'comment'=>$comment]);
                }
                if($exam['examsetting']['examtype']==2 and empty(input('exam'))){
                    $examend=date("Y-m-d H:i:s",strtotime("+".$exam['examsetting']['examtime']."minutes",strtotime($exam['examsetting']['starttime'])));
                    strtotime($examend) < time()?$useType=5:$useType=2;
                    return $this->fetch('preview',['useType'=>$useType,'title'=>$sectionInfo['title'],'exam'=>$exam,'info'=>$sectionInfo]);
                }else{
                    $now=$exam['examsetting']['starttime']?$exam['examsetting']['starttime']:date('Y-m-d H:i:s', time());
                    if(empty(session(is_user_login().$exam['id'].'endtime'))){
                        $end=date("Y-m-d H:i:s",strtotime("+".$exam['examsetting']['examtime']."minutes",strtotime($now)));
                        session(is_user_login().$exam['id'].'endtime',$end);
                    }else{
                        $end=session(is_user_login().$exam['id'].'endtime');
                    }
                    return $this->fetch('exam',['useType'=>3,'now'=>date('Y-m-d H:i:s', time()),'end'=>$end,'title'=>$sectionInfo['title'],'exam'=>$exam,'myexam'=>$myexam,'info'=>$sectionInfo,'secList'=>$section,'note'=>$note,'comment'=>$comment]);
                }
            }
        }
        if(hashids_decode(input('type'))==2){
            $sectionInfo=model('liveSection')->where(['id'=>hashids_decode(input('id'))])->find();
            $section=model('liveCourse')->getSection($sectionInfo['csid']);
            $note=model('notes')->where(['uid'=>is_user_login(),'cid'=>$sectionInfo['csid'],'sid'=>$sectionInfo['id'],'cstype'=>2])->order('addtime desc')->select();
            $comment=model('comment')->where(['cid'=>$sectionInfo['csid'],'sid'=>$sectionInfo['id'],'cstype'=>2])->limit(10)->order('addtime desc')->select();
            if($sectionInfo['sectype']==1){
                $now=date('Y-m-d h:i:s', time());
                return $this->fetch('livelearn',['title'=>$sectionInfo['title'],'now'=>$now,'info'=>$sectionInfo,'secList'=>$section,'note'=>$note,'comment'=>$comment,'isOver'=>isLiveOver($sectionInfo['starttime'],$sectionInfo['duration'])]);
            }
            if($sectionInfo['sectype']==2){
                return $this->fetch('audio',['title'=>$sectionInfo['title'],'info'=>$sectionInfo,'secList'=>$section,'note'=>$note,'comment'=>$comment]);
            }
            if($sectionInfo['sectype']==3){
                model('userCourse')->where(['uid'=>is_user_login(),'cid'=>$sectionInfo['csid']])->update(['nowstudy'=>$sectionInfo['id']]);
                return $this->fetch('document',['title'=>$sectionInfo['title'],'info'=>$sectionInfo,'secList'=>$section,'note'=>$note,'comment'=>$comment]);
            }
            if($sectionInfo['sectype']==4){
                $exam=model('exams')->where('id',$sectionInfo['paperid'])->find();
                $exam['examsetting']=json_to_array($exam['examsetting']);
                $exam['examquestions']=json_to_array($exam['examquestions']);
                $subQuestions=[];
                foreach ($exam['examquestions'] as $k => $value) {
                    if(get_question_mark($k)=='TiMao'){
                        foreach ($exam['examquestions'][$k] as $i => $value) {
                            $subQuestions[$value]=$this->getSubQuestions($value);
                        }
                    }
                }
                $exam['subQuestions']=$subQuestions;
                $myexam=model('myexam')->where(['uid'=>is_user_login(),'cid'=>$sectionInfo['csid'],'eid'=>$sectionInfo['paperid']])->find();
                $myexam['myanswer']=json_to_array($myexam['myanswer']);
                $myexam['myscore']=json_to_array($myexam['myscore']);
                $myexam['myresult']=json_to_array($myexam['myresult']);
                if($exam['examsetting']['examtype']==1 || $myexam['ispost']==1){
                    return $this->fetch('exam',['useType'=>4,'title'=>$sectionInfo['title'],'exam'=>$exam,'myexam'=>$myexam,'info'=>$sectionInfo,'secList'=>$section,'note'=>$note,'comment'=>$comment]);
                }
                if($exam['examsetting']['examtype']==2 and empty(input('exam'))){
                    $examend=date("Y-m-d H:i:s",strtotime("+".$exam['examsetting']['examtime']."minutes",strtotime($exam['examsetting']['starttime'])));
                    strtotime($examend) < time()?$useType=5:$useType=2;
                    return $this->fetch('preview',['useType'=>$useType,'title'=>$sectionInfo['title'],'exam'=>$exam,'info'=>$sectionInfo]);
                }else{
                    $now=$exam['examsetting']['starttime']?$exam['examsetting']['starttime']:date('Y-m-d H:i:s', time());
                    if(empty(session(is_user_login().$exam['id'].'endtime'))){
                        $end=date("Y-m-d H:i:s",strtotime("+".$exam['examsetting']['examtime']."minutes",strtotime($now)));
                        session(is_user_login().$exam['id'].'endtime',$end);
                    }else{
                        $end=session(is_user_login().$exam['id'].'endtime');
                    }
                    return $this->fetch('exam',['useType'=>3,'now'=>date('Y-m-d H:i:s', time()),'end'=>$end,'title'=>$sectionInfo['title'],'exam'=>$exam,'myexam'=>$myexam,'info'=>$sectionInfo,'secList'=>$section,'note'=>$note,'comment'=>$comment]);
                }
            }
        }
    }
    /**
     * 根据题帽ID获取题帽题子题
     */
    function getSubQuestions($id){
        $getSubQuestions= model('questions')->field('id')->where('questionparent',$id)->column('id');
        return $getSubQuestions;
    }
    /**
     * 考试测试结果提交
     */
    public function exampPost(){
        $param = $this->request->param();
        $zhuGuanNum=0;
        $myexam['kgscores']=0;
        foreach ($param['answer'] as $k=> $value) {
            if(is_array($value)){
                $value=implode($value);
            }
            $myexam['myanswer'][$k]=$value;
            if(in_array( get_question_mark(get_question_type_id($k)),['SingleSelect','MultiSelect','TrueOrfalse'])){
                if(get_question_mark(get_question_type_id($k))=='MultiSelect'){
                    if(check_m_answer($k,$value)==1){
                        $myexam['myresult'][$k]=1;
                        $myexam['myscore'][$k]=$param['questionscore'][$k];
                        $myexam['kgscores']=($myexam['kgscores']+$param['questionscore'][$k]);
                    }
                    if(check_m_answer($k,$value)==2){
                        $myexam['myresult'][$k]=2;
                        $myexam['myscore'][$k]=$param['questionscore'][$k]-3;
                        $myexam['kgscores']=($myexam['kgscores']+$myexam['myscore'][$k]);
                    }
                    if(check_m_answer($k,$value)==3){
                        $myexam['myresult'][$k]=2;
                        $myexam['myscore'][$k]=0;
                    }
                }else{
                    if(check_answer($k,$value)){
                        $myexam['myresult'][$k]=1;
                        $myexam['myscore'][$k]=$param['questionscore'][$k];
                        $myexam['kgscores']=($myexam['kgscores']+$param['questionscore'][$k]);
                    }else{
                        $myexam['myresult'][$k]=2;
                        $myexam['myscore'][$k]=0;
                    }
                }
            }
            if(in_array( get_question_mark(get_question_type_id($k)),['FillInBlanks','ShortAnswer','TiMao'])){
                $zhuGuanNum++;
            }
        }
        if($zhuGuanNum==0){
            $myexam['totalscores']=$myexam['kgscores'];
            $myexam['status']=1;
        }

        $myexam['uid']=is_user_login();
        $myexam['eid']=$param['eid'];
        $myexam['cid']=$param['cid'];
        $myexam['tid']=getTeachetId($param['cid'],$param['ctype']);
        $myexam['ctype']=$param['ctype'];
        $myexam['myscore']=json_encode($myexam['myscore']);
        $myexam['myanswer']=json_encode($myexam['myanswer']);
        $myexam['myresult']=json_encode($myexam['myresult']);
        $myexam['ispost']=1;
        $myexam['uid']=is_user_login();
        $myexam['addtime']=date('Y-m-d H:i:s', time());
        if($this->insert('myexam', $myexam) === true){
            $this->examstudied($myexam['uid'],$myexam['cid'],$param['sid'],$myexam['ctype']);
            $this->success('交卷成功');
            session(is_user_login().$param['eid'].'endtime','');
        }else {
            $this->error($this->errorMsg);
        }
    }
    /**
     * 写入考试记录
     */
    public function examstudied($uid,$cid,$sid,$type){
        if(!$uid){
            $this->error('登录失效，请重新登录');
        }
        $res=db('learned')->where(['cid'=>$cid,'sid'=>$sid,'type'=>$type,'uid'=>$uid])->find();
        if(!empty($res) and $uid){
            db('learned')->where('id', $res['id'])->update(['status'=>1]);
        }else{
            db('learned')->insert(['status'=>1,'cid'=>$cid,'sid'=>$sid,'type'=>$type,'uid'=>$uid,'addtime'=>date('y-m-d h:i:s',time())]);
        }
    }
    /**
     * 写入课程学习记录
     */
    public function studied(){
        $param = $this->request->param();
        if(!is_user_login()){
            echo json_encode(['status'=>2]);exit();
        }
        $res=db('learned')->where(['cid'=>$param['cid'],'sid'=>$param['sid'],'type'=>$param['type'],'uid'=>is_user_login()])->find();
        if(!empty($res) and is_user_login()){
            if(db('learned')->where('id', $res['id'])->update(['status'=>1,'seek'=>0])){
                echo json_encode(['status'=>1]);exit();
            }else{
                echo json_encode(['status'=>3]);exit();
            }
        }
        if(empty($res) and is_user_login()){
            if(db('learned')->insert(['cid'=>$param['cid'],'sid'=>$param['sid'],'type'=>$param['type'],'uid'=>is_user_login(),'status'=>1,'seek'=>0,'addtime'=>date('y-m-d h:i:s',time())])){
                echo json_encode(['status'=>1]);exit();
            }
        }
    }
    /**
     * 写入正在学习章节
     */
    public function nowStudy(){
        $param = $this->request->param();
        $res=db('learned')->where(['cid'=>$param['cid'],'sid'=>$param['sid'],'type'=>$param['type'],'uid'=>is_user_login()])->find();
        if(empty($res) and is_user_login()){
            db('learned')->insert(['cid'=>$param['cid'],'sid'=>$param['sid'],'type'=>$param['type'],'uid'=>is_user_login(),'laststudy'=>$param['sid'],'status'=>0,'duration'=>0,'addtime'=>date('y-m-d h:i:s',time())]);
        }
        if(!empty($res) and is_user_login()){
            db('learned')->where('id', $res['id'])->update(['laststudy'=>$param['sid'],'addtime'=>date('y-m-d h:i:s',time())]);
        }
    }
    /**
    * 写入正在学习时长
    */
    public function addduration(){
        $param = $this->request->param();
        $res=db('learned')->where(['cid'=>$param['cid'],'sid'=>$param['sid'],'type'=>$param['type'],'uid'=>is_user_login()])->find();
        if(is_user_login() && $res){
            db('learned')->where('id', $res['id'])->update(['laststudy'=>$param['sid'],'duration'=>$res['duration']+$param['duration'],'seek'=>$param['seek'],'addtime'=>date('y-m-d h:i:s',time())]);
        }
    }
    /**
     * 远程获进入直播间地址，只有域名授权的才可以获取到
     */
    public function getLiveUrl(){
        $param = $this->request->param();
        $room_id=$param['room_id'];
        $config=$this->get_site_info(2);
        $url = $config['server'] . "/educloud/educloud/getLiveUrl";
        $userInfo=model('user')->where(['id'=>is_user_login()])->find();
        $cid=model('liveSection')->where('room_id',$room_id)->value('csid');
        $sid=model('liveSection')->where('room_id',$room_id)->value('id');
        $tid=model('liveCourse')->where('id',$cid)->value('teacher_id');
        if($tid==getTeacherIdByUid(is_user_login()) or getAdminAuthId(is_admin_login())==1){
            $userRole=1;
        }else{
            $userRole=0;
        }
        $this->examstudied(is_user_login(),$cid,$sid,2);
        $postdata = array_merge($config,['room_id'=>$room_id,'user_number'=>$userInfo['id'],'user_name'=>$userInfo['username'],'user_role'=>$userRole,'user_avatar'=>is_https().get_domain().defaultAvatar($userInfo['avatar'])]);
        $res= json_decode(post_curl($url, $postdata),true);
        $res['user_number']=$userInfo['id'];
        $res['user_name']=$userInfo['username'];
        $res['user_role']=$userRole;
        $res['user_avatar']=is_https().get_domain().defaultAvatar($userInfo['avatar']);
        echo json_encode($res);

    }
    /**
     * 远程获进入直播间签名
     */
    public function getLiveSign(){
        $param = $this->request->param();
        $room_id=$param['room_id'];
        $config=$this->get_site_info(2);
        $url = $config['server'] . "/educloud/educloud/getLiveSingn";
        $userInfo=model('user')->where(['id'=>is_user_login()])->find();
        $cid=model('liveSection')->where('room_id',$room_id)->value('csid');
        $sid=model('liveSection')->where('room_id',$room_id)->value('id');
        $tid=model('liveCourse')->where('id',$cid)->value('teacher_id');
        if($tid==getTeacherIdByUid(is_user_login()) or getAdminAuthId(is_admin_login())==1){
            $userRole=1;
        }else{
            $userRole=0;
        }
        $this->examstudied(is_user_login(),$cid,$sid,2);
        $postdata = array_merge($config,['room_id'=>$room_id,'user_number'=>$userInfo['id'],'user_name'=>$userInfo['username'],'user_role'=>$userRole,'user_avatar'=>is_https().get_domain().defaultAvatar($userInfo['avatar'])]);
        echo post_curl($url, $postdata);
    }
    /**
     * 远程获取直播回放播放凭证，只有域名授权的才可以获取到
     */
    public function getLivePlayBacToken(){
        $param = $this->request->param();
        $room_id=$param['room_id'];
        $cid=model('liveSection')->where('room_id',$room_id)->value('csid');
        $sid=model('liveSection')->where('room_id',$room_id)->value('id');
        $config=$this->get_site_info(2);
        $this->examstudied(is_user_login(),$cid,$sid,2);
        $url = $config['server'] . "/educloud/educloud/getLivePlayBacToken";
        $postdata = array_merge($config,['room_id'=>$room_id]);
        echo post_curl($url, $postdata);
    }
    /**
     * 远程获取点播播放凭证，只有域名授权的才可以获取到
     */
    public function getplaytoken(){
        $param = $this->request->param();
        $info = $this->get_site_info(1);
        $url = config('author_web') . "/educloud/alivideo/getplayertoken";
        $postdata = ['domain' => $info['domain'], 'authorcode' => $info['authorcode'],'KeyID' => $info['KeyID'], 'keySecret' => $info['KeySecret'], 'VideoId'=>$param['vid']];
        $output['state'] = true;
        $output['code'] = 1;
        $output['msg'] = "success";
        echo $output;
    }
    /**
     * 远程获取视频详情
     */
    public function getvideoinfo($videoId){
        $url = config('author_web') . "/educloud/alivideo/getvideoinfo";
        $postdata = ['KeyID' => config('KeyID'), 'keySecret' => config('KeySecret'), 'VideoId'=>$videoId];
        $restemp = json_to_array(post_curl($url, $postdata));
        return $restemp['Video'];
    }
    /**
     * 检查是否购买了课程有效期
     */
    public function checkValid ($type,$sid){
        if($type==1){
            $sectionInfo=model('videoSection')->field('csid,isfree,previewtimes')->where(['id'=>$sid])->find();
            $courseInfo=model('videoCourse')->field('id,youxiaoqi,teacher_id,type')->where(['id'=>$sectionInfo['csid']])->find();
        }
        if($type==2){
            $sectionInfo=model('liveSection')->field('csid,isfree,previewtimes')->where(['id'=>$sid])->find();
            $courseInfo=model('liveCourse')->field('id,youxiaoqi,teacher_id,type')->where(['id'=>$sectionInfo['csid']])->find();
        }
        $remain=get_course_last_time($courseInfo,2);
        if($courseInfo['youxiaoqi']==0 || !$remain || $sectionInfo['isfree']==1 || $sectionInfo['previewtimes']>0 || getAdminAuthId(is_admin_login())==1 || $courseInfo['teacher_id']==getTeacherIdByUid(is_user_login())){
            return true;
        }elseif($remain){
            $this->error('课程有效期已过，无法继续学习！');
            exit();
        }
    }
    /**
     * ajax根据是否购买课程获取课程资料下载信息
     */
    public function downMaterial(){
        $param = $this->request->param();
        if($param['type']==1){
            $tid = model('videoCourse')->where(['id'=>$param['cid']])->value('teacher_id');
        }
        if($param['type']==2){
            $tid = model('liveCourse')->where(['id'=>$param['cid']])->value('teacher_id');
        }
        $state=model('userCourse')->where(['cid'=>$param['cid'],'type'=>$param['type'],'uid'=>is_user_login()])->find();
        $downHref=model('material')->where(['id'=>$param['mid']])->value('oss_url');
        if($state || ($tid==getTeacherIdByUid(is_user_login())) || (getAdminAuthId(is_admin_login())==1)){
            echo (json_encode(['code'=>'1','downHref'=>'http://'.$downHref]));
        }else{
            echo (json_encode(['code'=>'0','msg'=>'请先购买课程']));
        }
    }
    /**
     * ajax添加笔记
     */
    public function addNotes(){
        $param = $this->request->param();
        $param['addtime']=date("Y-m-d H:i:s",time());
        $param['uid']=is_user_login();
        if ($id=model('notes')->insertGetId($param)){
            echo (json_encode(['code'=>'1','id'=>$id]));
        }else{
            echo (json_encode(['code'=>'0','msg'=>$this->error($this->errorMsg)]));
        }
    }
    /**
     * ajax获取笔记
     */
    public function getNotes(){
        $param = $this->request->param();
        $note=model('notes')->where(['id'=>$param['id']])->find();
        echo (json_encode($note));
    }
    /**
     * ajax删除笔记
     */
    public function delNotes(){
        if ($this->delete('notes', $this->request->param()) === true) {
            echo (json_encode(['code'=>'1','msg'=>'删除成功']));
        } else {
            echo (json_encode(['code'=>'0','msg'=>$this->error($this->errorMsg)]));
        }
    }
    /**
     * ajax添加评论
     */
    public function addComment(){
        $param = $this->request->param();
        $param['addtime']=date("Y-m-d H:i:s",time());
        $param['uid']=is_user_login();
        if ($id=model('comment')->insertGetId($param)){
            echo (json_encode(['code'=>'1','id'=>$id]));
        }else{
            echo (json_encode(['code'=>'0','msg'=>$this->error($this->errorMsg)]));
        }
    }
    /**
     * ajax获取评论
     */
    public function getComment(){
        $param = $this->request->param();
        $note=model('comment')->where(['id'=>$param['id']])->find();
        echo (json_encode($note));
    }
    /**
     * ajax删除评论
     */
    public function delComment(){
        if ($this->delete('comment', $this->request->param()) === true) {
            echo (json_encode(['code'=>'1','msg'=>'删除成功']));
        } else {
            echo (json_encode(['code'=>'0','msg'=>$this->error($this->errorMsg)]));
        }
    }
    /**
     * ajax收藏课程
     */
    public function favourite(){
        if(is_user_login()<=0){
            echo (json_encode(['code'=>'0','msg'=>'请先登录系统']));
        }else{
            $param = $this->request->param();
            $param['uid']=is_user_login();
            if(db('favourite')->insert($param)){
                echo (json_encode(['code'=>'1','msg'=>'收藏成功']));
            }else{
                echo (json_encode(['code'=>'0','msg'=>$this->error($this->errorMsg)]));
            }
        }
    }
    public function unfavourite(){
        if(is_user_login()<=0){
            echo (json_encode(['code'=>'0','msg'=>'请先登录系统']));
        }else{
            $param = $this->request->param();
            if(db('favourite')->where(['uid'=>is_user_login(),'cid'=>$param['cid'],'type'=>$param['type']])->delete()){
                echo (json_encode(['code'=>'2','msg'=>'取消收藏成功']));
            }else{
                echo (json_encode(['code'=>'0','msg'=>$this->error($this->errorMsg)]));
            }
        }

    }
}